package com.mcxx.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcxx.common.exception.BizException;
import com.mcxx.common.service.ReferenceService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.order.dto.OrderCertDTO;
import com.mcxx.modules.miniSalvation.order.param.ReferenceParam;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderCertReadService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.service.DefaultRestService;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.HttpServiceUtil;
import com.yinhai.ta404.core.utils.UUIDUtils;
import com.yinhai.ta404.core.validate.annotation.V;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Api("证明材料控制类")
@RestController
@RequestMapping("reference/v2")
public class ReferenceController extends DefaultRestService {
    private final static Logger logger = LoggerFactory.getLogger(ReferenceController.class);

    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private TmpOrderCertReadService tmpOrderCertReadService;
    @Autowired
    private ReferenceService referenceService;
    @Autowired
    private FileService fileService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Value("${yinhai.ocr.serviceKey}")
    private String ocrServiceKey;
    @Value("${yinhai.ocr.url}")
    private String ocrUrl;
    @Value("${yinhai.data-sync.access-key}")
    private String accessKey;


    @PostMapping("upload")
    @ApiOperation(value="上传证明材料",notes="上传证明材料")
    public void upload(@RequestParam("file") MultipartFile file, OrderCertDTO orderCertDTO) {
        if(file.isEmpty()){
            throw new BizException("上传的文件是空的");
        }

        orderCertDTO.setUserLevel(Integer.parseInt(getCurUserAccount().getAreaLevel()));
        Map<String, String> data = referenceService.upload(file, orderCertDTO);
        setData(data);
        logger.info("证明材料上传成功，结果：{}",data);
    }


    @PostMapping("deleteById")
    @ApiOperation(value="根据id删除证明材料",notes="根据id删除证明材料")
    public void deleteById(@V("notnull") String id,String businessType) {
        String level = getCurUserAccount().getAreaLevel();
        referenceService.deleteById(id, businessType, Integer.parseInt(level));
        logger.info("根据id删除证明材料成功");
    }


    @PostMapping("batchDelete")
    @ApiOperation(value="批量删除",notes="批量删除")
    public void batchDelete(@V("notnull") String ids,String businessType) {
        String[] idArr = ids.split(",");
        logger.info("开始批量删除，参数：{},{}",idArr,businessType);
        referenceService.batchDelete(idArr,businessType);
        logger.info("批量删除完成");
    }


    @PostMapping("batchUpdate")
    @ApiOperation(value="批量修改",notes="批量修改")
    public void batchUpdate(@V("notnull") String ids,String businessType,String nid) {
        String[] idArr = ids.split(",");
        logger.info("开始批量修改，参数：{},{}",idArr,businessType,nid);
        referenceService.batchUpdate(idArr,businessType,nid);
        logger.info("批量修改完成");
    }


    @GetMapping("upload_images")
    @ApiOperation("根据类型查询证明材料")
    public void listByType(ReferenceParam referenceParam) {
        logger.info("根据类型查询证明材料，参数是{}", JSON.toJSONString(referenceParam));
        List<Map<String, String>> list;
        if (Constant.BusinessCode.LINSHI.equals(referenceParam.getBusinessType())) {
            list = tmpOrderCertReadService.listByType(referenceParam);
        }else {
            list = orderCertReadService.listByType(referenceParam);
        }
        setData(list);
        logger.info("根据类型查询证明材料完成，结果是{}",JSON.toJSONString(list));
    }


    @Deprecated
    @GetMapping("upload_images/{key}")
    @ApiOperation("查看图片")
    public void viewImage(@PathVariable @V("notnull") String key, HttpServletResponse response) {
        try {
            byte[] buf = fileService.download(key);
            response.reset();
            response.setContentType("image/jpeg;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            out.write(buf);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("countByTypes")
    @ApiOperation("统计某一组类型下面的证明材料数量")
    public void countByTypes(@RequestBody ReferenceParam referenceParam) {
        logger.info("开始统计某一组类型下面的证明材料数量，参数是{}", JSON.toJSONString(referenceParam));
        List<Map<String, Object>> countResult;
        if (Constant.BusinessCode.LINSHI.equals(referenceParam.getBusinessType())) {
            countResult = tmpOrderCertReadService.countByTypes(referenceParam);
        } else{
            countResult = orderCertReadService.countByTypes(referenceParam);
        }
        setData(countResult);
        logger.info("统计某一组类型下面的证明材料数量完成，结果为{}", JSON.toJSONString(countResult));
    }

    @PostMapping("countByTypesWithLevel")
    @ApiOperation("统计某一组类型下面的证明材料数量")
    public void countByTypesWithLevel(@RequestBody ReferenceParam referenceParam) {
        referenceParam.setUserLevel(getCurUserAccount().getOrgLevel());
        logger.info("开始统计某一组类型下面的证明材料数量，参数是{}", JSON.toJSONString(referenceParam));
        List<Map<String, Object>> countResult;
        if (Constant.BusinessCode.LINSHI.equals(referenceParam.getBusinessType())) {
            countResult = tmpOrderCertReadService.countByTypes(referenceParam);
        } else {
            countResult = orderCertReadService.countByTypes(referenceParam);
        }
        setData(countResult);
        logger.info("统计某一组类型下面的证明材料数量完成，结果为{}", JSON.toJSONString(countResult));
    }


    @GetMapping("getHtmlById")
    @ApiOperation("通过orderId获取低保特困备份的html")
    public void getBackUpHtml(@RequestParam String orderId) {
       logger.info("通过orderId获取低保特困备份的html，参数是{}", orderId);

       String objKey = orderReadService.getOrderObjKey(orderId);
       setData(objKey);
       logger.info("通过orderId获取低保特困备份的html完成，结果是{}", objKey);
    }

    @GetMapping("/detailhtml")
    @ResponseBody
    public void html(@RequestParam String orderId,String businessCode,HttpServletResponse response) throws ServletException, IOException {
        String objKey = null;
        if(!CommonUtil.invalidArgs(businessCode)&&"500".equals(businessCode)){
            objKey = tmpOrderReadService.getOrderObjKey(orderId);
        }else{
            objKey = orderReadService.getOrderObjKey(orderId);
        }
        PrintWriter pw = null;
        if(StringUtils.isNotBlank(objKey)){
            try {
                byte[] bytes = fileService.download(objKey);
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html; charset=utf-8");
                pw = response.getWriter();;
                pw.println(new String(bytes));
                pw.flush();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException("-1","查看html异常");
            }finally {
                pw.close();
            }
        }
    }

    @PostMapping("idCardIdentity")
    @ApiOperation("上传身份证图片后调用OCR接口后返回身份证信息")
    public void idCardIdentity(@RequestParam("file") MultipartFile imgFile) {
        try {
            String uuid = UUIDUtils.getUUID();

            File file = new File(System.getProperty("java.io.tmpdir")+System.getProperty("file.separator")+uuid+".jpg");
            FileUtils.copyInputStreamToFile(imgFile.getInputStream(), file);
            String res = HttpServiceUtil.callServiceWithFileByOkHttp(ocrServiceKey,accessKey,ocrUrl,file,null);
            Map<String,Object> resMap = new HashMap<>();
            if(StringUtils.isNotBlank(res)){
                JSONObject resJson = JSONObject.parseObject(res);
                JSONObject dataJson = resJson.getJSONObject("data");
                JSONObject resultJson = dataJson.getJSONObject("result");
                JSONObject wordsResult = resultJson.getJSONObject("words_result");
                String idcard = wordsResult.getJSONObject("公民身份号码").getString("words");
                String name = wordsResult.getJSONObject("姓名").getString("words");
                String address = wordsResult.getJSONObject("住址").getString("words");
                String sex = wordsResult.getJSONObject("性别").getString("words");
                String birth = wordsResult.getJSONObject("出生").getString("words");
                resMap.put("idcard",idcard);
                resMap.put("name",name);
                resMap.put("address",address);
                resMap.put("sex",sex);
                resMap.put("birth",birth);
            }
            setData(resMap);

            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
